<template>
    <div class="login-container">
        <el-card class="login-card" shadow="always">
            <div class="login-header">
                <h2 class="login-title">用户登录</h2>
            </div>
            <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="0">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"
                        prefix-icon="Lock"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitLogin(), logintime()" style="width: 48%;">登录</el-button>
                    <el-button @click="resetForm" style="width: 48%; margin-left: 4%;">重置</el-button>
                </el-form-item>
                <div class="register-link">
                    还没有账号？
                    <a href="#" @click.prevent="gotoClick('/register')" class="register-button">立即注册</a>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const store = useStore();
const router = useRouter();
const userip = ref("");

onMounted(() => {
    fetchIPAddress();
});

const loginForm = ref({
    username: "",
    password: "",
});

const rules = {
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const loginFormRef = ref(null);

const gotoClick = (url) => {
    router.push({ path: url });
};

const submitLogin = () => {
    loginFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const response = await axios.post(
                    "http://localhost:3000/api/logins/login",
                    loginForm.value
                );
                if (response.data && response.data.token) {
                    const userToken = "Bearer " + response.data.token;
                    store.dispatch("updateToken", userToken);
                    ElMessage.success(response.data.message || "登录成功");
                    router.push("/");
                } else {
                    console.error("服务器响应数据格式错误");
                    ElMessage.error("服务器响应数据格式错误");
                }
            } catch (error) {
                console.error("登录请求失败:", error);
                ElMessage.error("登录失败，请检查用户名和密码");
            }
        } else {
            console.log("错误输入!");
            ElMessage.error("请检查输入信息");
        }
    });
};

async function logintime() {
    try {
        localStorage.removeItem("honey-admin");
        localStorage.setItem("loginTime", new Date().toLocaleString());
        await axios.post("http://localhost:3000/api/users/logintime/", {
            logintime: localStorage.getItem("loginTime"),
            username: loginForm.value.username,
            userip: userip.value,
        });
    } catch (error) {
        console.log(error);
    }
}

async function fetchIPAddress() {
    try {
        const response = await axios.get("http://localhost:3000/api/users/loginip/");
        userip.value = response.data.loginip;
    } catch (error) {
        console.error(error);
    }
}

const resetForm = () => {
    loginFormRef.value.resetFields();
};
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #f0f2f5, #cfd9df);
    padding: 20px;
}

.login-card {
    width: 380px;
    padding: 30px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
    border-radius: 12px;
    background-color: #ffffff;
}

.login-header {
    text-align: center;
    margin-bottom: 35px;
}

.login-title {
    font-size: 28px;
    color: #333;
    margin: 0 0 8px 0;
    font-weight: 600;
}

.login-subtitle {
    color: #909399;
    font-size: 16px;
}

:deep(.el-form-item) {
    margin-bottom: 25px;
}

:deep(.el-input) {
    --el-input-height: 45px;
    font-size: 14px;
}

:deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    padding: 0 15px;
    transition: all 0.2s;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-input__prefix) {
    display: flex;
    align-items: center;
    margin-right: 8px;
}

:deep(.el-icon) {
    font-size: 18px;
    color: #909399;
}

:deep(.el-input__inner) {
    margin-left: 4px;
}

.el-button {
    width: 100%;
    height: 45px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 4px;
    margin-top: 10px;
    transition: all 0.3s;
}

.el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.register-link {
    text-align: center;
    margin-top: 20px;
    color: #606266;
    font-size: 14px;
}

.register-button {
    color: #409eff;
    text-decoration: none;
    margin-left: 4px;
    font-weight: bold;
    cursor: pointer;
}

.register-button:hover {
    color: #66b1ff;
    text-decoration: underline;
}
</style>